<template>
  <el-card>
    <div class="btn">
      <el-button type="primary" @click="(dialogVisible = true), (isAdd = true)"
        ><i class="el-icon-plus"></i> 新增</el-button
      >
      <el-button
        type="success"
        @click="handleUser"
        :disabled="
          multipleSelection.length == 0 || multipleSelection.length > 1
        "
        ><i class="el-icon-edit"></i> 修改</el-button
      >
      <el-button
        type="danger"
        :disabled="multipleSelection.length == 0"
        @click="deleteActive"
        ><i class="el-icon-delete"></i> 删除</el-button
      >
    </div>
    <el-table
      :data="tableData"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column type="index" width="50" label="编号"> </el-table-column>
      <el-table-column prop="addPeople" label="发布人"> </el-table-column>
      <el-table-column prop="title" label="活动名称"> </el-table-column>
      <el-table-column prop="classifyName" label="活动类别"> </el-table-column>
      <el-table-column
        prop="description"
        label="活动描述"
        class-name="description-column"
        :show-overflow-tooltip="false">
        <template slot-scope="scope">
          <span class="description-text">
            {{ scope.row.description.length > 8 ? scope.row.description.slice(0, 8) + '...' : scope.row.description }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="活动状态">
        <template slot-scope="scope">
          <el-tag :type="getStatusType(scope.row)" :effect="'light'">
            {{ getStatusText(scope.row) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="beginTime" label="活动开始时间"> </el-table-column>
      <el-table-column prop="endTime" label="活动截止时间"> </el-table-column>
      <el-table-column prop="place" label="活动地点"> </el-table-column>
      <el-table-column prop="numberOfParticipants" label="参与人数">
      </el-table-column>
      <el-table-column prop="numberOfPeopleUpperLimit" label="人数上限">
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage4"
      :page-sizes="[5, 10, 15]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"></el-pagination>
    <el-dialog
      title="添加活动"
      :visible.sync="dialogVisible"
      width="70%"
      :before-close="handleClose"
    >
      <el-form :model="form" :rules="rules" ref="form">
        <el-form-item label="活动名称" prop="title">
          <el-input v-model="form.title"></el-input>
        </el-form-item>
        <el-form-item label="活动地点" prop="place">
          <el-input v-model="form.place"></el-input>
        </el-form-item>
        <el-select v-model="form.classifyId" placeholder="活动分类">
          <el-option
            v-for="item in options"
            :key="item.id"
            :label="item.title"
            :value="item.id"
          >
          </el-option>
        </el-select>
        <el-form-item label="活动描述" prop="description">
          <el-input v-model="form.description"></el-input>
        </el-form-item>
        <el-form-item label="活动可报人数" prop="numberOfPeopleUpperLimit">
          <el-input v-model="form.numberOfPeopleUpperLimit"></el-input>
        </el-form-item>
        <el-date-picker
          v-model="form.beginTime"
          type="datetime"
          format="yyyy-MM-dd HH:mm:ss"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="活动开始时间"
          style="width: 11vw"
        ></el-date-picker>
        <el-date-picker
          v-model="form.endTime"
          type="datetime"
          format="yyyy-MM-dd HH:mm:ss"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="活动结束时间"
          style="margin-left: 3vw; width: 11vw"
        >
        </el-date-picker>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="addActivity">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="修改活动"
      :visible.sync="dialogVisible2"
      width="70%"
      :before-close="handleClose"
    >
      <el-form :model="changeForm" :rules="rules" ref="changeForm">
        <el-form-item label="活动名称" prop="title">
          <el-input v-model="changeForm.title"></el-input>
        </el-form-item>
        <el-form-item label="活动地点" prop="place">
          <el-input v-model="changeForm.place"></el-input>
        </el-form-item>
        <el-select v-model="changeForm.classifyId" placeholder="活动分类">
          <el-option
            v-for="item in options"
            :key="item.id"
            :label="item.title"
            :value="item.id"
          >
          </el-option>
        </el-select>
        <el-form-item label="活动描述" prop="description">
          <el-input v-model="changeForm.description"></el-input>
        </el-form-item>
        <el-form-item label="活动可报人数" prop="numberOfPeopleUpperLimit">
          <el-input v-model="changeForm.numberOfPeopleUpperLimit"></el-input>
        </el-form-item>
        <el-date-picker
          v-model="changeForm.beginTime"
          format="yyyy-MM-dd HH:mm:ss"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="datetime"
          placeholder="活动开始时间"
          style="width: 11vw"
        ></el-date-picker>
        <el-date-picker
          format="yyyy-MM-dd HH:mm:ss"
          value-format="yyyy-MM-dd HH:mm:ss"
          v-model="changeForm.endTime"
          type="datetime"
          placeholder="活动结束时间"
          style="margin-left: 3vw; width: 11vw"
        >
        </el-date-picker>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="changeActivity()">确 定</el-button>
      </span>
    </el-dialog>
  </el-card>
</template>

<script>
import {
  addActivity,
  changeActivity,
  deleteActive,
  getActivity
} from '@/api/activity'
import instance from '@/utils/request'

export default {
  data () {
    return {
      tableData: [],
      multipleSelection: [],
      dialogVisible: false,
      dialogVisible2: false,
      options: [],
      form: {
        title: '',
        description: '',
        beginTime: '',
        endTime: '',
        place: '',
        numberOfParticipants: '',
        numberOfPeopleUpperLimit: '',
        classifyId: ''
      },
      changeForm: {
        id: '',
        title: '',
        description: '',
        beginTime: '',
        endTime: '',
        place: '',
        numberOfParticipants: '',
        numberOfPeopleUpperLimit: '',
        classifyId: '',
        classifyName: ''
      },
      isAdd: true,
      rules: {
        title: [
          { required: true, message: '请输入活动标题', trigger: 'blur' },
          {
            min: 2,
            max: 12,
            message: '长度在 2 到 12 个字符',
            trigger: 'blur'
          }
        ],
        description: [
          { required: true, message: '请输入活动内容', trigger: 'blur' },
          {
            min: 3,
            max: 20,
            message: '长度在 3 到 20 个字符',
            trigger: 'blur'
          }
        ],
        place: [
          {
            required: true,
            message: '请输入活动地点',
            trigger: 'blur'
          }
        ],
        beginTime: [
          { required: true, message: '请输入开始时间', trigger: 'blur' }
        ],
        endTime: [
          { required: true, message: '请输入结束时间', trigger: 'blur' }
        ],
        numberOfPeopleUpperLimit: [
          { required: true, message: '请输入上限人数', trigger: 'blur' }
        ],
        classifyName: [
          { required: true, message: '请输入活动分类', trigger: 'blur' }
        ]
      },
      page: 1,
      pageSize: 10,
      total: 1,
      currentPage4: 1
    }
  },
  created () {
    this.getActivity()
    instance('/api/classify/all').then((data) => {
      this.options = data.data
    })
  },
  methods: {
    getActivity () {
      getActivity(this.page, this.pageSize)
        .then((data) => {
          console.log('活动列表数据：', data)
          if (data.code === 1 && data.data) {
            this.total = data.data.total
            this.tableData = data.data.rows.map(item => ({
              ...item,
              beginTime: item.beginTime ? item.beginTime.replace('T', ' ') : '',
              endTime: item.endTime ? item.endTime.replace('T', ' ') : ''
            }))
          } else {
            this.tableData = []
            this.total = 0
            this.$message.error('获取活动列表失败')
          }
        })
        .catch((error) => {
          console.error('获取活动列表失败：', error)
          this.tableData = []
          this.total = 0
          this.$message.error('获取活动列表失败')
        })
    },
    handleSelectionChange (val) {
      this.multipleSelection = val
    },
    handleClose () {
      this.$confirm('关闭话框，新增内容将消失', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          if (this.isAdd) {
            this.dialogVisible = false
            // 重置表单
            this.form = {
              title: '',
              description: '',
              beginTime: '',
              endTime: '',
              place: '',
              numberOfParticipants: '',
              numberOfPeopleUpperLimit: '',
              classifyId: ''
            }
          } else {
            this.dialogVisible2 = false
          }
        })
        .catch(() => {})
    },
    addActivity () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          addActivity(this.form).then((data) => {
            if (data.code === 1) {
              this.$message({
                message: '添加成功',
                type: 'success'
              })
              this.dialogVisible = false
              // 重置表单
              this.form = {
                title: '',
                description: '',
                beginTime: '',
                endTime: '',
                place: '',
                numberOfParticipants: '',
                numberOfPeopleUpperLimit: '',
                classifyId: ''
              }
              this.getActivity()
            } else {
              this.$message.error(data.msg || '添加失败')
            }
          }).catch(error => {
            console.error('添加活动失败：', error)
            this.$message.error('添加活动失败')
          })
        }
      })
    },
    handleUser () {
      this.dialogVisible2 = true
      this.isAdd = false
      const selectedActivity = JSON.parse(JSON.stringify(this.multipleSelection[0]))
      this.changeForm = {
        ...selectedActivity,
        beginTime: selectedActivity.beginTime ? selectedActivity.beginTime.replace('T', ' ') : '',
        endTime: selectedActivity.endTime ? selectedActivity.endTime.replace('T', ' ') : ''
      }
    },
    changeActivity () {
      this.$refs.changeForm.validate((valid) => {
        if (valid) {
          changeActivity(this.changeForm).then((data) => {
            if (data.code === 1) {
              this.$message({
                message: '修改成功',
                type: 'success'
              })
              this.dialogVisible2 = false
              this.getActivity()
            } else {
              this.$message.error(data.msg || '修改失败')
            }
          }).catch(error => {
            console.error('修改活动失败：', error)
            this.$message.error('修改活动失败')
          })
        }
      })
    },
    deleteActive () {
      this.$confirm('此操作将永久删除选中的活动，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const idList = this.multipleSelection.map((data) => data.id)
        deleteActive(idList).then((data) => {
          if (data.code === 1) {
            this.$message({
              message: '删除成功',
              type: 'success'
            })
            this.getActivity()
          } else {
            this.$message.error(data.msg || '删除失败')
          }
        }).catch(error => {
          console.error('删除活动失败：', error)
          this.$message.error('删除活动失败')
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleSizeChange (val) {
      this.pageSize = val
      this.getActivity()
    },
    handleCurrentChange (val) {
      this.page = val
      this.getActivity()
    },
    // 获取活动状态类型
    getStatusType (row) {
      const now = new Date()
      const beginTime = new Date(row.beginTime)
      const endTime = new Date(row.endTime)

      if (now < beginTime) {
        return 'info' // 未开始
      } else if (now >= beginTime && now <= endTime) {
        return 'success' // 进行中
      } else {
        return 'danger' // 已结束
      }
    },

    // 获取活动状态文本
    getStatusText (row) {
      const now = new Date()
      const beginTime = new Date(row.beginTime)
      const endTime = new Date(row.endTime)

      if (now < beginTime) {
        return '未开始'
      } else if (now >= beginTime && now <= endTime) {
        return '进行中'
      } else {
        return '已结束'
      }
    }
  }
}
</script>

<style scoped>
.el-form > .el-form-item,
.el-form > .el-select {
  width: 25vw;
  margin-right: 8vw;
}

.el-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

/* 活动描述文字样式 */
.description-text {
  display: inline-block;
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
